package com.jz.main.io.websocket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class WebSocketClient2 {

    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("localhost", 8080);
        System.out.println("Connected to server.");

        BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

        new Thread(() -> {
            try {
                String response;
                while ((response = in.readLine()) != null) {
                    System.out.println("Received from server: " + response);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();

        String userInputStr;
        while ((userInputStr = userInput.readLine()) != null) {
            out.println(userInputStr);

            if ("exit".equalsIgnoreCase(userInputStr)) {
                break;
            }
        }

        socket.close();
        System.out.println("Disconnected from server.");
    }
}
